<template>
  <div class="base-upload">
    <el-upload
      v-bind="$attrs"
      :file-list="fileList"
      :action="config.url"
      :headers="config.headers"
      :on-success="handleSuccess"
    >
      <!--默认插槽-->
      <slot v-if="slots.default !== undefined && attrs.drag === undefined"></slot>
      <el-button
        v-if="slots.default === undefined && attrs.drag === undefined"
        :icon="UploadFilled"
        type="primary"
      >
        点击上传
      </el-button>
      <!--拖拽上传-->
      <div v-if="attrs.drag !== undefined">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件放在此处或<em>单击上传</em></div>
      </div>
      <!--tips-->
      <template #tip>
        <slot v-if="slots.tip !== undefined" name="tip"></slot>
        <div v-else class="el-upload__tip">{{ fileTips }}</div>
      </template>
    </el-upload>
  </div>
</template>
<script setup>
import { getToken } from '@/utils/auth';
import { UploadFilled } from '@element-plus/icons-vue';

const emit = defineEmits(['update:fileList']);

const props = defineProps({
  fileList: {
    type: Array,
    default: () => [],
  },
  url: {
    type: String,
    required: true,
  },
  fileTips: {
    type: String,
    default: '文件上传提示信息',
  },
});

const slots = useSlots();
const attrs = useAttrs();

const config = reactive({
  headers: {
    Authorization: 'Bearer ' + getToken(),
  },
  url: import.meta.env.VITE_APP_BASE_API + props.url,
});

const handleSuccess = (response, file, fileList) => {
  if (response?.data) {
    emit('update:fileList', fileList);
  }
};
</script>
